package signHelper.dao;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import signHelper.modle.Major;
import signHelper.modle.School;
import signHelper.modle.User;

@Repository
public class MajorDao {
	private final Logger logger = LogManager.getLogger(getClass());
	private static final RowMapper<Major> rm = JdbcHelper.getRowMapper(Major.class);
	private @Autowired JdbcTemplate jdbcTemplate;
	private @Autowired NamedParameterJdbcTemplate namedParameterJdbcTemplate;
	
	public Major add(Major param) {
		param.setId(JdbcHelper.insertAndGetKey(namedParameterJdbcTemplate,Sql.ADD, param));
		return param;
	}
	
	public Major getById(Integer id){
		return JdbcHelper.queryForObject(jdbcTemplate, Sql.GET_BY_ID, rm, id);
	}
	
	public List<Major> query(Major param,Integer has,Integer nextSize) {
		StringBuffer sql = new StringBuffer(Sql.GET);
		if (StringUtils.isNotBlank(param.getName())) {
			sql.append(" and name=:name");
		}
		if (param.getInstitutionId()!=null) {
			sql.append(" and institution_id=:institutionId");
		}
		if(has!=null&&nextSize!=null)
			sql.append(" limit ").append(has).append(",").append(nextSize);
		return namedParameterJdbcTemplate.query(sql.toString(), JdbcHelper.getSqlParameterSource(param), rm);
	}
	
	public void update(Major bean) {
		namedParameterJdbcTemplate.update(Sql.UPDATE, JdbcHelper.getSqlParameterSource(bean));
	}
	
	public void delete(Integer id) {
		jdbcTemplate.update(Sql.DEL_BY_ID, id);
	}
	
	private class Sql {
		public static final String GET = "select * from major where 1=1";
		public static final String GET_BY_ID = "select * from major where id=?";
		public static final String ADD = "insert into major (name,institution_id,code, create_date,update_date) values (:name,:institutionId,:code,now(),now())";
		public static final String DEL_BY_ID = "delete from major where id=?";
		public static final String UPDATE = "update major set name=ifnull(:name,name),institution_id=ifnull(:institutionId,institution_id),code=ifnull(:code,code) where id=:id";
	}


	
}
